package com.nhjf.admin.controller.coursesSeries;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import com.nhjf.admin.common.util.SysProperties;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.admin.util.PictureUtil;
import com.nhjf.command.coursesSeries.CoursesSeriesCommand;
import com.nhjf.common.page.Pagination;
import com.nhjf.model.coursesSeries.CoursesSeries;
import com.nhjf.model.system.Role;
import com.nhjf.model.system.User;
import com.nhjf.model.teachers.Courses;
import com.nhjf.model.teachers.CoursesType;
import com.nhjf.model.teachers.OperationLog;
import com.nhjf.model.teachers.Teacher;
import com.nhjf.pojo.dto.result.ServiceResultDto;
import com.nhjf.pojo.qo.coursesSeries.CoursesSeriesQo;
import com.nhjf.pojo.qo.teachers.CoursesQo;
import com.nhjf.pojo.qo.teachers.CoursesTypeQo;
import com.nhjf.pojo.qo.teachers.TeachersQo;
import com.nhjf.service.coursesSeries.CoursesSeriesService;
import com.nhjf.service.teachers.CoursesService;
import com.nhjf.service.teachers.CoursesTypeService;
import com.nhjf.service.teachers.OperationLogService;
import com.nhjf.service.teachers.TeachersService;

import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("coursesSeries")
public class CoursesSeriesController {
	@Autowired
	private CoursesSeriesService coursesSeriesService;
	@Autowired
	private TeachersService teacherService;
	@Autowired
	private CoursesTypeService coursesTypeService;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private CoursesService coursesService;
	@Autowired
	private TeachersService teachersService;
	//分页列表
	@RequestMapping("/coursesSeries_page")
	public String series_page(HttpServletRequest request, @ModelAttribute CoursesSeriesQo coursesSeriesQo, Model model, @RequestParam(value = "page", defaultValue = "1") Integer page) {
		if (coursesSeriesQo == null) {
			coursesSeriesQo = new CoursesSeriesQo();
		}
		User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
		Set<Role> set= user.getRoleList();
		Iterator<Role> iter = set.iterator();
		Role roles=new Role();
		while(iter.hasNext()) {
			roles=iter.next();
			break;
		}
		if("1".equals(roles.getNumber())) {
			coursesSeriesQo.setSeachTeacher(true);
			coursesSeriesQo.setIsSeriesLesson(1);
			Pagination pagination = new Pagination();
			pagination.setPageSize(6);
			pagination.setCondition(coursesSeriesQo);
			pagination.setPageNo(page);
			pagination = coursesSeriesService.queryPagination(pagination);
			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("CoursesQo", coursesSeriesQo);
			model.addAttribute("webPath",webPath);
			model.addAttribute("pagination", pagination);
			model.addAttribute("type", 1);
			return "/coursesSeries/coursesSeries_Home.html";
		} else if("3".equals(roles.getNumber())) {
			coursesSeriesQo.setSeachTeacher(true);
			coursesSeriesQo.setIsSeriesLesson(1);
			Pagination pagination = new Pagination();
			pagination.setPageSize(6);
			TeachersQo teachersQo=new  TeachersQo();
			teachersQo.setUserId(user.getId());
			Teacher teacher= teacherService.queryUnique(teachersQo);
			coursesSeriesQo.setUploader(teacher.getId());
			pagination.setCondition(coursesSeriesQo);
			pagination.setPageNo(page);
			pagination = coursesSeriesService.queryPagination(pagination);
			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("webPath",webPath);
			model.addAttribute("pagination", pagination);
			model.addAttribute("CoursesQo", coursesSeriesQo);
			model.addAttribute("type", 3);
			return "/coursesSeries/coursesSeries_Home.html";
		}else if("2".equals(roles.getNumber())) {
			coursesSeriesQo.setSeachTeacher(true);
			coursesSeriesQo.setIsSeriesLesson(1);
			Pagination pagination = new Pagination();
			pagination.setPageSize(6);
			TeachersQo teachersQo=new  TeachersQo();
			teachersQo.setUserId(user.getId());

			Teacher teacher= teacherService.queryUnique(teachersQo);
			coursesSeriesQo.setAffiliation(teacher.getTraininginstitution().getId());
			coursesSeriesQo.setIsSeriesLesson(1);
			pagination.setCondition(coursesSeriesQo);
			pagination.setPageNo(page);
			pagination = coursesSeriesService.queryPagination(pagination);

			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("CoursesQo", coursesSeriesQo);
			model.addAttribute("webPath",webPath);
			model.addAttribute("pagination", pagination);
			model.addAttribute("type", 2);

			return "/coursesSeries/coursesSeries_Home.html";
		}
		return "/coursesSeries/coursesSeries_Home.html";

	}
	//查看本系列课
	@RequestMapping("/coursesSeries_seriesLesson")
	public String coursesSeries_seriesLesson(Model model,String id, @RequestParam(value = "page", defaultValue = "1") Integer page) {
		CoursesQo coursesQo=new CoursesQo();
		coursesQo.setSeachCoursesSeries(true);
		coursesQo.setSeachUploader(true);
		coursesQo.setSeriesId(Long.parseLong(id));
		Pagination pagination = new Pagination();
		pagination.setPageSize(10);
		pagination.setCondition(coursesQo);
		pagination.setPageNo(page);
		pagination = coursesService.queryPagination(pagination);
		model.addAttribute("pagination",pagination);
		SysProperties sysProperties=SysProperties.getInstance();
		String webPath=sysProperties.get("webPath");
		model.addAttribute("webPath",webPath);
		return "/coursesSeries/coursesSeries_lesson.html";
	}
	//跳转系列课添加页面
	@RequestMapping("/coursesSeries_add")
	public String tz_coursesSeriesadd(Model model) {
		CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
		coursesTypeQo.setType(1);
		List<CoursesType> coursesType =coursesTypeService.queryList(coursesTypeQo);
		model.addAttribute("coursesType",coursesType);
		return "/coursesSeries/coursesSeries_add.html";
	}
	//课程添加
	@ResponseBody
	@RequestMapping(value= "/courseSeries_adds")
	public String save(MultipartFile pic,HttpServletRequest request,HttpServletResponse response,CoursesSeriesQo qo) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role roles=new Role();
			while(iter.hasNext()) {
				roles=iter.next();
				break;
			}
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			qo.setPrice(null);
			if("1".equals(roles.getNumber())) {
				return "505";
			} else if("2".equals(roles.getNumber()) || "2".equals(roles.getNumber())) {
				if (pic.isEmpty()) {
					resMap.put("code", "500");
					resMap.put("message", "上传图片不可为空");
					return JSONObject.fromObject(resMap).toString();
				}
				int returnTag = -1;
				SysProperties sysProperties=SysProperties.getInstance();
				String imgPath=sysProperties.get("imagePath");
				//获取图片原始文件名
				String originalFilename = pic.getOriginalFilename();
				System.out.println(originalFilename);
				//文件名使用当前时间
				String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
				// 获取上传图片的扩展名(jpg/png/...)
				String extension = FilenameUtils.getExtension(originalFilename);
				String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
				boolean flag = false;
				// 判断文件格式是否合法
				for (String str : regular) {
					if (extension.equalsIgnoreCase(str)) {
						flag = true;
					}
				}
				if (!flag) {
					returnTag = 0;
					resMap.put("code", "500");
					resMap.put("message", "上传图片格式不正确！");
					return JSONObject.fromObject(resMap).toString();
				}
				// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
				String path =imgPath + name + "." + extension;
				//图片上传的绝对路径

				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				// 上传图片
				pic.transferTo(new File(path));

				//保存课程信息
				TeachersQo teachersQo=new TeachersQo();
				teachersQo.setUserId(user.getId());
				Teacher teacher=teacherService.queryUnique(teachersQo);
				if(teacher==null) {
					return "500";
				}
				qo.setUploader(teacher.getId());
				qo.setSeachTeacher(true);
				qo.setCover(name + "." + extension);
				java.util.Date  date=new java.util.Date();
				qo.setCreationTime(date);
				qo.setIsReview(0);
				qo.setIsTopping(2);
				qo.setIsSeriesLesson(1);
				ServiceResultDto serviceResultDto=coursesSeriesService.findadd(qo);
				if(serviceResultDto.getSuccess()) {
					OperationLog operationLog=new OperationLog();
					operationLog.setOperationType(2);
					operationLog.setOperationDescription("系列课课添加!");
					operationLog.setUserId(user);
					operationLog.setOperationTime(new Date());
					operationLog.setOperationUserName(user.getUserName());
					operationLogService.save(operationLog);
					return "200";
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "500";
	}
	@ResponseBody
	@RequestMapping("/coursesType_Subctype")
	public String showSubctype(HttpServletRequest request, HttpServletResponse response, Model model,String typeOne) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
			coursesTypeQo.setpId(Long.parseLong(typeOne));
			coursesTypeQo.setType(2);
			List<CoursesType> list=coursesTypeService.queryList(coursesTypeQo);
			if(list!=null) {
				resMap.put("code", "200");
				resMap.put("message", list);
				return JSONObject.fromObject(resMap).toString();
			}else {
				return "404";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
	}
	@RequestMapping("/series_tzReview")
	public String series_tzReview(String id,Model model) {
		CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
		coursesSeriesQo.setCoursesSeriesId(Long.parseLong(id));
		CoursesSeries coursesSeries=coursesSeriesService.queryUnique(coursesSeriesQo);
		CoursesQo coursesQo=new CoursesQo();
		coursesQo.setSeachCoursesSeries(true);
		coursesQo.setSeriesId(coursesSeries.getId());
		coursesQo.setIsReview(0);
		List<Courses> courses=coursesService.queryList(coursesQo);
		if(coursesSeries.getIsReview()==1 && courses.size()<1) {
			return "重复操作!已经审核!";
		}
		if(coursesSeries.getIsRelease()!=2) {
			model.addAttribute("mes","请先发布");
			return "请先发布!";
		}
		if(coursesSeries.getIsPrice()==2 && coursesSeries.getPrice()==null) {
			model.addAttribute("shoufei",2);
		}
		model.addAttribute("series",coursesSeries);
		return "/coursesSeries/coursesSeries_review.html";
	}
	@RequestMapping("/series_review")
	@ResponseBody
	public String series_Review(HttpServletRequest request,HttpSession session,HttpServletResponse response,String id,String price) {
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			if(id==null && id=="") {
				return "500";
			}else{
				CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
				coursesSeriesQo.setSeachTeacher(true);
				coursesSeriesQo.setCoursesSeriesId(Long.parseLong(id));
				CoursesSeries cs=coursesSeriesService.queryUnique(coursesSeriesQo);
				CoursesQo coursesQo=new CoursesQo();
				coursesQo.setSeachCoursesSeries(true);
				coursesQo.setSeachUploader(true);
				coursesQo.setSeriesId(cs.getId());
				coursesQo.setIsReview(0);
				List<Courses> list=coursesService.queryList(coursesQo);
//				Courses courses=coursesService.queryUnique(coursesQo);
				for (Courses courses2 : list) {
					if(courses2!=null) {
						courses2.setIsReview(1);
						coursesService.update(courses2);
					}
				}
			
				if(cs.getIsReview()==0 && cs.getIsPrice()==2) {
					Integer sum=(int) (Double.parseDouble(price)*100);
					cs.setPrice(sum);
					cs.setIsReview(1);
					coursesSeriesService.update(cs);
					return "200";
				}else {
					cs.setIsReview(1);
					coursesSeriesService.update(cs);
					return "200";
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
	}
	@RequestMapping("/series_topping")
	@ResponseBody
	public String series_Topping(HttpServletRequest request,HttpSession session,HttpServletResponse response,String id) {
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			if(id==null && id=="") {
				return "500";
			}else{
				CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
				coursesSeriesQo.setSeachTeacher(true);
				coursesSeriesQo.setCoursesSeriesId(Long.parseLong(id));
				CoursesSeries cs=coursesSeriesService.queryUnique(coursesSeriesQo);
				if(cs.getIsTopping()==2) {
					cs.setIsTopping(1);
					coursesSeriesService.update(cs);
					return "200";
				}else if(cs.getIsReview()==1) {
					cs.setIsTopping(2);
					coursesSeriesService.update(cs);
					return "201";
				}
				else {
					return "505";
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
	}
	/**
	 * 是否绝学
	 * @param id
	 * @return
	 */
	@RequestMapping("/isSchooling")
	@ResponseBody
	public String isSchooling(String id) {
		CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
		coursesSeriesQo.setSeachTeacher(true);
		coursesSeriesQo.setCoursesSeriesId(Long.parseLong(id));
		CoursesSeries coursesSeries= coursesSeriesService.queryUnique(coursesSeriesQo);
		if(coursesSeries!=null) {
			if(coursesSeries.getIsSchooling()==null) {
				coursesSeries.setIsSchooling(1);
				coursesSeriesService.update(coursesSeries);
				return "200";
			}
			if(coursesSeries.getIsSchooling()==1) {
				coursesSeries.setIsSchooling(2);
				coursesSeriesService.update(coursesSeries);
				return "201";
			}else {
				coursesSeries.setIsSchooling(1);
				coursesSeriesService.update(coursesSeries);
				return "200";
			}
		}
		return "500";
	}
	@RequestMapping("/series_delete")
	@ResponseBody
	public String series_Delete(HttpServletRequest request,HttpSession session,HttpServletResponse response,String id) {
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			if(id==null && id=="") {
				return "500";
			}else{
				CoursesQo coursesQo=new CoursesQo();
				coursesQo.setSeachCoursesSeries(true);
				coursesQo.setSeachUploader(true);
				CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
				coursesSeriesQo.setSeachTeacher(true);
				coursesSeriesQo.setCoursesSeriesId(Long.parseLong(id));
				CoursesSeries coursesSeries=coursesSeriesService.queryUnique(coursesSeriesQo);
				TeachersQo teachersQo=new TeachersQo();
				teachersQo.setSeachOrganization(true);
				teachersQo.setSeachUser(true);
				teachersQo.setTeacherId(coursesSeries.getUploader().getId());
				Teacher teacher=teachersService.queryUnique(teachersQo);
				teacher.setCoursesNum(teacher.getCoursesNum()-1);
				teachersService.update(teacher);
				coursesQo.setSeriesId(coursesSeries.getId());
				List<Courses> cs= coursesService.queryList(coursesQo);
				SysProperties sysProperties=SysProperties.getInstance();
				for (Courses courses : cs) {
					String videoPath=sysProperties.get("fileUploadPath");
					File dest2 = new File(videoPath+courses.getVideo());
					if(dest2.isFile() && dest2.exists()) {
						dest2.delete();
					}
					coursesService.deleteById(courses.getId());
				}
				
				String imgPath=sysProperties.get("imagePath");
				File dest = new File(imgPath+coursesSeries.getCover());
				// 路径为文件且不为空则进行删除  
				if (dest.isFile() && dest.exists()) {  
					dest.delete();  
				}
				coursesSeriesService.deleteById(Long.parseLong(id));
				OperationLog operationLog=new OperationLog();
				operationLog.setOperationType(1);
				operationLog.setOperationDescription("系列课删除!");
				operationLog.setUserId(user);
				operationLog.setOperationTime(new Date());
				operationLog.setOperationUserName(user.getUserName());
				operationLogService.save(operationLog);
			}
			return "200";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "500";
		}
	}
	@RequestMapping("/newCourses")
	public String tznewCourses(Model model) {
		CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
		coursesTypeQo.setType(1);
		List<CoursesType> coursesType =coursesTypeService.queryList(coursesTypeQo);
		model.addAttribute("coursesType",coursesType);
		return "/Courses/courses/courses_newAdd.html";
	}
	@RequestMapping("/modify_toSeries")
	public String modify_toSeries(String id,Model model) {
		CoursesQo coursesQo=new CoursesQo();
		coursesQo.setSeachCoursesSeries(true);
		coursesQo.setSeachUploader(true);
		coursesQo.setCoursesId(Long.parseLong(id));
		Courses courses=coursesService.queryUnique(coursesQo);
		model.addAttribute("courses",courses);
		CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
		coursesTypeQo.setType(1);
		List<CoursesType> coursesType =coursesTypeService.queryList(coursesTypeQo);
		model.addAttribute("coursesType",coursesType);
		SysProperties sysProperties=SysProperties.getInstance();
		String webPath=sysProperties.get("webPath");
		model.addAttribute("webPath",webPath);
		return "/coursesSeries/coursesSeries_modify.html";
	}
	@ResponseBody
	@RequestMapping(value= "/courseSeries_update")
	public String update(HttpServletRequest request, HttpServletResponse response, Model model,String fileName,CoursesSeriesCommand command) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			SysProperties sysProperties1=SysProperties.getInstance();
			String fileTemPath=sysProperties1.get("temporaryFileUploadPath");
			String filePath=sysProperties1.get("fileUploadPath");
			SysProperties sysProperties=SysProperties.getInstance();
			String imgPath=sysProperties.get("imagePath");
			if ( user== null) {
				// 跳转到登录页面
				response.sendRedirect(request.getContextPath()+"/login");
			}
			if(command.getCoursesId()==null) {
				resMap.put("code", "404");
				resMap.put("message", "没有此账号！");
				return JSONObject.fromObject(resMap).toString();
			}
			CoursesQo coursesQo=new CoursesQo();
			coursesQo.setCoursesId(command.getCoursesId());
			Courses courses=coursesService.queryUnique(coursesQo);
			MultipartFile pic = null;
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (isMultipart){ 
				MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
				pic = multipartRequest.getFile("pic");
				if(pic==null) {
					if(StringUtils.isNotBlank(fileName)) {
						PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
						File source = new File(filePath+user.getId()+"/"+fileName);
						Encoder encoder = new Encoder();
						String length = "";
						MultimediaInfo m = encoder.getInfo(source);
						System.out.println("-------"+m.getDuration());
						long ls = m.getDuration()/1000;
						int hour = (int) (ls/3600);
						int minute = (int) (ls/60);
						int second = (int) (ls-hour*3600-minute*60);
						length = minute+":"+second;
						command.setViewTime(length);
						command.setVideo(user.getId()+"/"+fileName);
						String delfile=filePath+courses.getVideo();
						File delvidel = new File(delfile);
						// 路径为文件且不为空则进行删除  
						if (delvidel.isFile() && delvidel.exists()) {  
							delvidel.delete();  
						}
						PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
					}
					ServiceResultDto ts= coursesService.mudifyCommand(command);
					if(ts.getSuccess()) {
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(3);
						operationLog.setOperationDescription("系列课修改!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						return "200";
					}
				}else {


					String imge =imgPath+courses.getCoursesSeries().getCover();
					File dest = new File(imge);
					// 路径为文件且不为空则进行删除  
					if (dest.isFile() && dest.exists()) {  
						dest.delete();  
					}
					if (pic.isEmpty()) {
						resMap.put("code", "500");
						resMap.put("message", "上传图片不可为空");
						return JSONObject.fromObject(resMap).toString();
					}
					int returnTag = -1;

					// 获取图片原始文件名
					String originalFilename = pic.getOriginalFilename();
					System.out.println(originalFilename);
					//文件名使用当前时间
					String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
					// 获取上传图片的扩展名(jpg/png/...)
					String extension = FilenameUtils.getExtension(originalFilename);
					String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
					boolean flag1 = false;
					// 判断文件格式是否合法
					for (String str : regular) {
						if (extension.equalsIgnoreCase(str)) {
							flag1 = true;
						}
					}
					if (!flag1) {
						returnTag = 0;
						resMap.put("code", "500");
						resMap.put("message", "上传图片格式不正确！");
						return JSONObject.fromObject(resMap).toString();
					}
					// 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
					String path =imgPath + name + "." + extension;
					//图片上传的绝对路径
					File dir = new File(path);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					// 上传图片
					pic.transferTo(new File(path));
					if(StringUtils.isNotBlank(fileName)) {
						command.setVideo(user.getId()+"/"+fileName);
						String delfile=filePath+courses.getVideo();
						File delvidel = new File(delfile);
						// 路径为文件且不为空则进行删除  
						if (delvidel.isFile() && delvidel.exists()) {  
							delvidel.delete();  
						}
						PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
						File source = new File(filePath+user.getId()+"/"+fileName);
						Encoder encoder = new Encoder();
						String length = "";
						MultimediaInfo m = encoder.getInfo(source);
						System.out.println("-------"+m.getDuration());
						long ls = m.getDuration()/1000;
						int hour = (int) (ls/3600);
						int minute = (int) (ls/60);
						int second = (int) (ls-hour*3600-minute*60);
						length = minute+":"+second;
						command.setViewTime(length);
					}
					command.setCover(name + "." + extension);
					ServiceResultDto ts= coursesService.mudifyCommand(command);
					if(ts.getSuccess()) {
						OperationLog operationLog=new OperationLog();
						operationLog.setOperationType(3);
						operationLog.setOperationDescription("系列课课修改!");
						operationLog.setUserId(user);
						operationLog.setOperationTime(new Date());
						operationLog.setOperationUserName(user.getUserName());
						operationLogService.save(operationLog);
						return "200";
					}
				}
			}else {
				if(StringUtils.isNotBlank(fileName)) {
					command.setVideo(user.getId()+"/"+fileName);
					String delfile=filePath+courses.getVideo();
					File delvidel = new File(delfile);
					// 路径为文件且不为空则进行删除  
					if (delvidel.isFile() && delvidel.exists()) {  
						delvidel.delete();  
					}
					PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
				}
				ServiceResultDto ts=coursesService.mudifyCommand(command);
			}

		} catch (Exception e) {
			// TODO: handle exception
			return "500";
		}
		return "500";
	}
	//去系列课修改页面
	@RequestMapping("/tz_update")
	public String tz_update(String id,Model model) {
		CoursesTypeQo coursesTypeQo=new CoursesTypeQo();
		coursesTypeQo.setType(1);
		List<CoursesType> coursesType =coursesTypeService.queryList(coursesTypeQo);
		model.addAttribute("coursesType",coursesType);
		CoursesSeriesQo seriesQo=new CoursesSeriesQo();
		seriesQo.setCoursesSeriesId(Long.parseLong(id));
		seriesQo.setSeachTeacher(true);
		CoursesSeries coursesSeries=coursesSeriesService.queryUnique(seriesQo);
		if(null!=coursesSeries ) {
			SysProperties sysProperties=SysProperties.getInstance();
			String webPath=sysProperties.get("webPath");
			model.addAttribute("courses",coursesSeries);
			model.addAttribute("webPath",webPath);
		}
		return "/coursesSeries/coursesSeries_update.html";
	}
	//课程修改course_update
	@ResponseBody
	@RequestMapping(value= "/courseSeries_update1")
	public String update1(HttpServletRequest request, HttpServletResponse response, Model model,CoursesSeriesQo q) {
		Map<String, Object> resMap=new HashMap<String, Object>();
		try {
			User user=(User)Jurisdiction.getSession().getAttribute(com.nhjf.common.Constants.USER_INFO);
			Set<Role> set= user.getRoleList();
			Iterator<Role> iter = set.iterator();
			Role roles=new Role();
			while(iter.hasNext()) {
				roles=iter.next();
				break;
			}
			if("1".equals(roles.getNumber())) {
				SysProperties sysProperties1=SysProperties.getInstance();
				//					String fileTemPath=sysProperties1.get("temporaryFileUploadPath");
				//					String filePath=sysProperties1.get("fileUploadPath");
				SysProperties sysProperties=SysProperties.getInstance();
				String imgPath=sysProperties.get("imagePath");
				if ( user== null) {
					// 跳转到登录页面
					response.sendRedirect(request.getContextPath()+"/login");
				}
				q.setPrice(null);
				if(q.getCoursesSeriesId()==null) {
					resMap.put("code", "404");
					resMap.put("message", "没有此账号！");
					return JSONObject.fromObject(resMap).toString();
				}
				CoursesSeriesQo coursesSeriesQo=new CoursesSeriesQo();
				coursesSeriesQo.setCoursesSeriesId(q.getCoursesSeriesId());
				CoursesSeries series=coursesSeriesService.queryUnique(coursesSeriesQo);
				MultipartFile pic = null;
				boolean isMultipart = ServletFileUpload.isMultipartContent(request);
				if (isMultipart){ 
					MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
					pic = multipartRequest.getFile("pic");
					if(pic==null) {
						//							if(StringUtils.isNotBlank(fileName)) {
						//								PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
						//								File source = new File(filePath+user.getId()+"/"+fileName);
						//								Encoder encoder = new Encoder();
						//								String length = "";
						//								MultimediaInfo m = encoder.getInfo(source);
						//								System.out.println("-------"+m.getDuration());
						//								long ls = m.getDuration()/1000;
						//								int hour = (int) (ls/3600);
						//								int minute = (int) (ls/60);
						//								int second = (int) (ls-hour*3600-minute*60);
						//								length = minute+":"+second;
						//								q.setViewTime(length);
						//								q.setVideo(user.getId()+"/"+fileName);
						//								String delfile=filePath+courses.getVideo();
						//								File delvidel = new File(delfile);
						//								// 路径为文件且不为空则进行删除  
						//								if (delvidel.isFile() && delvidel.exists()) {  
						//									delvidel.delete();  
						//								}
						//								PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
						//							}
						ServiceResultDto ts= coursesSeriesService.findpmodify(q);
						if(ts.getSuccess()) {
							OperationLog operationLog=new OperationLog();
							operationLog.setOperationType(3);
							operationLog.setOperationDescription("课程修改!");
							operationLog.setUserId(user);
							operationLog.setOperationTime(new Date());
							operationLog.setOperationUserName(user.getUserName());
							operationLogService.save(operationLog);
							return "200";
						}
					}else {


						String imge =imgPath+series.getCover();
						File dest = new File(imge);
						// 路径为文件且不为空则进行删除  
						if (dest.isFile() && dest.exists()) {  
							dest.delete();  
						}
						if (pic.isEmpty()) {
							resMap.put("code", "500");
							resMap.put("message", "上传图片不可为空");
							return JSONObject.fromObject(resMap).toString();
						}
						int returnTag = -1;

						// 获取图片原始文件名
						String originalFilename = pic.getOriginalFilename();
						System.out.println(originalFilename);
						//文件名使用当前时间
						String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
						// 获取上传图片的扩展名(jpg/png/...)
						String extension = FilenameUtils.getExtension(originalFilename);
						String[] regular = { "JPG", "GIF","PNG","JPEG" ,"BMP"};
						boolean flag1 = false;
						// 判断文件格式是否合法
						for (String str : regular) {
							if (extension.equalsIgnoreCase(str)) {
								flag1 = true;
							}
						}
						if (!flag1) {
							returnTag = 0;
							resMap.put("code", "500");
							resMap.put("message", "上传图片格式不正确！");
							return JSONObject.fromObject(resMap).toString();
						}
						//图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
						String path =imgPath + name + "." + extension;
						//图片上传的绝对路径
						File dir = new File(path);
						if (!dir.exists()) {
							dir.mkdirs();
						}
						// 上传图片
						pic.transferTo(new File(path));
						//							if(StringUtils.isNotBlank(fileName)) {
						//								q.setVideo(user.getId()+"/"+fileName);
						//								String delfile=filePath+courses.getVideo();
						//								File delvidel = new File(delfile);
						//								// 路径为文件且不为空则进行删除  
						//								if (delvidel.isFile() && delvidel.exists()) {  
						//									delvidel.delete();  
						//								}
						//								PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
						//							}
						//							PictureUtil.copyFile(fileTemPath+user.getId()+"/"+fileName, filePath+user.getId()+"/"+fileName);
						//							File source = new File(filePath+user.getId()+"/"+fileName);
						//							Encoder encoder = new Encoder();
						//							String length = "";
						//							MultimediaInfo m = encoder.getInfo(source);
						//							System.out.println("-------"+m.getDuration());
						//							long ls = m.getDuration()/1000;
						//							int hour = (int) (ls/3600);
						//							int minute = (int) (ls/60);
						//							int second = (int) (ls-hour*3600-minute*60);
						//							length = minute+":"+second;
						//							q.setViewTime(length);
						q.setCover(name + "." + extension);
						ServiceResultDto ts= coursesSeriesService.findpmodify(q);
						if(ts.getSuccess()) {
							OperationLog operationLog=new OperationLog();
							operationLog.setOperationType(3);
							operationLog.setOperationDescription("课程修改!");
							operationLog.setUserId(user);
							operationLog.setOperationTime(new Date());
							operationLog.setOperationUserName(user.getUserName());
							operationLogService.save(operationLog);
							return "200";
						}
					}
				}
			}else {

			}
			//				

		} catch (Exception e) {
			// TODO: handle exception
			return "500";
		}
		return "500";
	}

}
